//
//  LoginViewController.swift
//  foreign_swift
//
//  Created by hdr on 15-4-9.
//  Copyright (c) 2015年 hdr. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController ,UITextFieldDelegate {
    
    
    //背景图片
    var backgroundImageView:UIImageView!
    
    var logoImageView:UIImageView!
    
    //用户名
    var usernameTf:UITextField!
    
    //密码框
    var passwordTf:UITextField!
    
    init(){
        super.init(nibName:nil,bundle:nil)
    }
   
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        //添加背景图片
        addBackgroundImage()
        
        //添加Logo
        addLogo()
        
        //增加输入框
        addTextField()
        
        addButton()
        
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        let emailText = textField.text ;
        
        if let range =  emailText.rangeOfString("@") {
            
            Config.shareInstance().setValue(textField.text, forKey: Config.key_email)
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        self.navigationController?.navigationBar.hidden = true;
        self.navigationController?.interactivePopGestureRecognizer.enabled = false;
        UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.None)
    }
    
    //添加背景图片
    func addBackgroundImage(){
        backgroundImageView = UIImageView(frame: Const.screen_frame)
        backgroundImageView.userInteractionEnabled = true
        backgroundImageView.image = UIImage(named: "choice_background.png")
        
        self.view.addSubview(backgroundImageView!)
    }
    
    func addLogo(){
        
        //用户名背景图片
        logoImageView = ViewHelper.initImageViewWithImageName("common_logo.png")
        logoImageView.center = CGPoint(x: Const.screen_width_center, y:Const.screen_height * 0.15)
        backgroundImageView?.addSubview(logoImageView)
        
    }
    
    func addTextField(){
        //设置用户名文本框和背景
        var usernameBgView = ViewHelper.initImageViewWithImageName("choice_account.png")
        usernameBgView.center = CGPoint(x: Const.screen_width_center, y: Const.screen_height*0.3)
        usernameBgView.userInteractionEnabled = true
        
        
        usernameTf = UITextField(frame: CGRect(x: 40, y: 2, width: usernameBgView.image!.size.width-40, height: 40))
        usernameTf.keyboardType = UIKeyboardType.EmailAddress
        usernameTf.enabled = true
        usernameTf.tintColor = UIColor.makeWithIntRGB(8,152,255)
        usernameTf.font = UIFont.systemFontOfSize(17)
        usernameTf.clearButtonMode = UITextFieldViewMode.WhileEditing
        usernameTf.delegate = self
        
        var email = Config.shareInstance().getStringValue(Config.key_email)
        
        usernameTf.text = email
        
        usernameBgView.addSubview(usernameTf)
        
        backgroundImageView.addSubview(usernameBgView)
        
        //设置密码框和背景
        var passwordBgView = ViewHelper.initImageViewWithImageName("choice_password")
        
        passwordBgView.center = CGPoint(x: Const.screen_width_center , y: usernameBgView.center.y + usernameBgView.bounds.height + 15)
        passwordBgView.userInteractionEnabled = true
        
        passwordTf = UITextField(frame: CGRect(x: 40, y: 2, width: passwordBgView.image!.size.width - 40, height: 40))
        passwordTf.clearButtonMode = UITextFieldViewMode.WhileEditing
        passwordTf.secureTextEntry = true
        
        passwordBgView.addSubview(passwordTf)
        backgroundImageView.addSubview(passwordBgView)
        
        usernameTf.text = "hdr@qq.com"
        passwordTf.text = "123456"
        
    }
    
    func addButton(){
        let loginBtnX = 60
        
        //添加登陆按钮
        var loginBtn = UIButton(frame: CGRect(x:loginBtnX, y: Int(Const.screen_height * 0.6),width:Int(Const.screen_width) - 2 * loginBtnX,height: 45))
        
        loginBtn.layer.cornerRadius = 8
        loginBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        loginBtn.setTitle("登陆", forState: UIControlState.Normal)
        loginBtn.backgroundColor = UIColor.normalBlueBtn
        loginBtn.titleLabel?.font = UIFont.systemFontOfSize(20)
        loginBtn.addTarget(self, action:"onLoginClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        backgroundImageView.addSubview(loginBtn)
        
        //添加注册按钮
        var registerBtn = UIButton(frame: CGRect(x: loginBtnX, y: Int(Const.screen_height*0.75), width: Int(Const.screen_width) - 2*loginBtnX, height: 45))
        registerBtn.layer.cornerRadius = 8
        registerBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        registerBtn.setTitle("注册", forState: UIControlState.Normal)
        registerBtn.addTarget(self, action:"onRegisterCklick", forControlEvents: UIControlEvents.TouchUpInside)
        registerBtn.backgroundColor = UIColor.normalRedBtn
        
        backgroundImageView.addSubview(registerBtn)
    }
    
    func onLoginClick(){
        
        var params = ["email":usernameTf.text,"password":passwordTf.text]
        Http.post(Urls.loginUrl, parameters: params)
        .success(self.onLoginSuccess)
        .failure(self.onLoginFalure)
        .showProgress(self)
    }
    
    func onLoginSuccess(data:JSON){

        //设置登陆标志
        Config.shareInstance().setValue(1, forKey: Config.key_login_mark)
        let mc  = MainController();
        var user = Converter.jsonToUser(data)
        user.nickName = user.accountName
        user.userType = Const.USER_TYPE_MASTER
        
        YolandaDb.saveUser(user)
        
        CurUser.curUser = user
        
        if let sessionkey = data["terminal_user_session_key"].stringValue {
            Http.session_key = sessionkey
            Config.shareInstance().setValue(sessionkey, forKey: "session_key")
        }else{
            println("返回的数据居然没有sessionkey?'")
        }
        
        self.dismissViewControllerAnimated(false, completion: nil)
        self.presentViewController(mc, animated: false, completion: nil)
        

    }
    
    func onLoginFalure(code:Int,msg:String?){
        if(code == 0){
            Alter.showInfoButtom(self,"网络不给力哦")
        }else if let msg = msg {
            Alter.showInfoButtom(self,msg)
        }
    }
    
    func onRegisterCklick(){
        NSLog("你点击了注册")
    }
}
